package com.example.data.dao;

import com.example.data.entity.DataDic;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

@Mapper
@Repository
public interface DataDicDAO {
    final static Logger logger = LoggerFactory.getLogger(DataDicDAO.class);
    /* 在java中写xml可读性和维护性太差，
     *所以这里借用内部类来生成动态SQL。
     *增改删查有对应的 @InsertProvider、@UpdateProvider、@DeleteProvider 、@SelectProvider
     * 可参考 ：https://www.cnblogs.com/guoyafenghome/p/9123442.html
     */

    /*
    @Select("<script> select * from data_dic " +
            "<if test=\"data_desc !=null \"> " +
            "where data_desc = #{data_desc} </if>" +
            " </script>")
    */
    @SelectProvider(type = DataDicDAOProvider.class, method = "queryData")
    List<DataDic> queryData(DataDic dataDic);

    /*查询data_dic全部数据，后期使用 pagehelper 做分页处理*/
    @Select("select * from data_dic ")
    List<DataDic> queryDataAll();

    @Insert("insert into data_dic(data_desc,data_category,data_no,editable) " +
            "values(#{data_desc},#{data_category},#{data_no},#{editable}) ")
     void  savaData(DataDic dataDic);

    @Update("update data_dic set data_category = #{data_category}," +
            "data_desc = #{data_desc},data_no = #{data_no}," +
            "editable = #{editable} where id = #{id}")
    void modify(DataDic dataDic);

    @Delete("delete from data_dic where id = #{id} ")
    void delete(DataDic dataDic);


    //内部类实现动态sql
    class DataDicDAOProvider{
        public String queryData(DataDic dataDic){
            //结构化sql
           /* FROM和WHERE：跟SELECT一样，可以写多个参数，也可以在多行重复使用，最终会智能合并而不会报错
            这样语句适用于写很长的SQL时，能够保证SQL结构清楚。便于维护，可读性高。*/
            return new SQL(){
                {
                SELECT("id,data_desc");
                SELECT("data_category,data_no");
                SELECT("editable");  //会智能合并
                FROM("data_dic");
                    if(dataDic.getData_category()!=null && !(dataDic.getData_category().equals("")) ){
                        WHERE("data_category like '%"+dataDic.getData_category()+"%' ");
                    }
                    if(dataDic.getData_desc()!=null && !(dataDic.getData_desc().equals("")) ){
                        WHERE("data_desc like '%"+dataDic.getData_desc()+"%' ");
                    }
                    if (dataDic.getData_no()!=null && !(dataDic.getData_no().equals("")) ){
                        WHERE("data_no = #{data_no}");
                    }
                    if (!StringUtils.isEmpty(dataDic.getId())){
                        WHERE("id = #{id}");
                    }
                }
            }.toString();

        }
    }

}
